<script setup lang='ts'>
import { useUserStore, useSystemStore, useStudentStore } from "./store"
const user = useUserStore()
const system = useSystemStore()

import { storeToRefs } from "pinia"

//pinia解构出来的变量不具有响应式
const { name, age } = storeToRefs(user)
// const {name,age} = user //这里不具有响应式

const showUser = () => {
  console.log(name.value, age.value)
}

const changeAge = () => {
  user.age++
}

const names: string[] = ["小明", "小黄", "小率", "小点", "小笑"]
const randomInt = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

const changeName = () => {
  user.name = names[randomInt(0, 4)]
}

//整体修改
const changeNameAndAge = () => {
  user.$patch({
    name: names[randomInt(0, 4)],
    age: user.age + 1
  })
  console.log(user.name, user.age)
}

const checkName = (age: number) => {
  if (age < 18) {
    return "未成年人"
  } else if (age >= 18 && age <= 30) {
    return "青年人"
  } else if (age > 30 && age < 60) {
    return "中年人"
  } else {
    return "老年人"
  }
}

//整体修改
const changeNameAndAge2 = () => {
  user.$patch((state) => {
    state.age = randomInt(1, 100)
    state.name = checkName(state.age)
  })
  console.log(user.name, user.age)
}

const changeNameAndAge3 = () => {
  user.$state = {
    name: "法外狂徒张三",
    age: 30
  }
}

const changeNameAndAge4 = () => {
  user.setNameAndAge("张三", 30)
}


//student
const studentStore = useStudentStore()
//单击事件触发
const getStudentInfo = () => {
  studentStore.setStudent(null)
}

//重置state
const resetStudentInfo = () => studentStore.$reset()


//当state里面的值被修改时，就会触发该事件
studentStore.$subscribe((args,state)=>{
  console.log("args===>",args)
  console.log("state===>",state)
})


studentStore.$onAction((args)=>{
  args.after(()=>{
    console.log("after")
  })
  console.log("onAction args===>",args)
})

</script>

<template>
  <div>
    <p>User Name:{{ user.name }}</p>
    <p>User Age: {{ user.age }}</p>
  </div>
  <div>
    <p>System Info: {{ system.systemInfo.version }}</p>
    <p>System Memory: {{ system.getMemory() }}</p>
  </div>
  <div>
    <button @click="changeAge">修改年龄</button>
    <button @click="changeName">修改姓名</button>
    <button @click="changeNameAndAge">整体修改</button>
    <button @click="changeNameAndAge2">整体修改2</button>
    <button @click="changeNameAndAge3">整体修改3</button>
    <button @click="changeNameAndAge4">整体修改4</button>
    <button @click="showUser">ShowUser</button>
  </div>

  <br>

  <div>
    <p>student name: {{ studentStore.student.name }}</p>
    <p>student grade: {{ studentStore.student.grade }}</p>
    <p>student fullName: {{ studentStore.getFullName }}</p>
    <p>student fullName2: {{ studentStore.getFullName2 }}</p>
    <p>student fullName3: {{ studentStore.getFullName3("张姓:") }}</p>

    <p>
      <button @click="getStudentInfo">查询学生信息</button>
      <button @click="resetStudentInfo">重置</button>
    </p>
  </div>
</template>

<style scoped></style>